<template>
  <div class="user-container">
    <a-card>
      <!-- 搜索区域 -->
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="用户名">
          <a-input v-model:value="searchForm.userName" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item label="手机号">
          <a-input v-model:value="searchForm.phone" placeholder="请输入手机号" />
        </a-form-item>
        <a-form-item label="角色">
          <a-select v-model:value="searchForm.userRole" placeholder="请选择角色" allowClear>
            <a-select-option v-for="(value, key) in USER_ROLE" :key="value" :value="value">
              {{ USER_ROLE_TEXT[value] }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">搜索</a-button>
          <a-button style="margin-left: 8px" @click="resetSearch">重置</a-button>
        </a-form-item>
      </a-form>

      <!-- 表格区域 -->
      <a-table
        :columns="columns"
        :data-source="userList"
        :loading="loading"
        :pagination="{
          ...pagination,
          showTotal: (total) => `总计 ${total} 条数据`
        }"
        @change="handleTableChange"
        style="margin-top: 16px"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'avatarUrl'">
            <a-avatar :src="record.avatarUrl">
              {{ record.userName?.charAt(0)?.toUpperCase() }}
            </a-avatar>
          </template>
          <template v-if="column.key === 'userRole'">
            <a-tag :color="USER_ROLE_COLOR[record.userRole]">
              {{ USER_ROLE_TEXT[record.userRole] }}
            </a-tag>
          </template>
          <template v-if="column.key === 'createTime'">
            {{ formatDateTime(record.createTime) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="handleEdit(record)">编辑</a-button>
              <a-popconfirm
                title="确定要删除这个用户吗？"
                @confirm="handleDelete(record)"
              >
                <a-button type="link" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 编辑用户弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
    >
      <a-form
        :model="userForm"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="头像" name="userAvatar">
          <upload-image
            v-model:value="userForm.userAvatar"
            :biz="BIZ_TYPE.USER_AVATAR"
          />
        </a-form-item>
        <a-form-item label="用户名" name="userName">
          <a-input v-model:value="userForm.userName" />
        </a-form-item>
        <a-form-item label="手机号" name="phone">
          <a-input v-model:value="userForm.phone" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="userForm.email" />
        </a-form-item>
        <a-form-item label="角色" name="userRole">
          <a-select v-model:value="userForm.userRole">
            <a-select-option v-for="(value, key) in USER_ROLE" :key="value" :value="value">
              {{ USER_ROLE_TEXT[value] }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { formatDateTime } from '@/utils/format';
import {
  listUserVoByPageUsingPost,  // 使用带 VO 的分页查询接口
  deleteUserUsingPost,
  updateUserUsingPost
} from '@/api/userController';
import UploadImage from '@/components/UploadImage.vue'
import { BIZ_TYPE } from '@/constants/upload'
import { USER_ROLE, USER_ROLE_TEXT, USER_ROLE_COLOR } from '@/constants/user'

// 搜索表单
const searchForm = ref({
  userName: '',
  phone: '',
  userRole: undefined as string | undefined
});

// 表格列定义
const columns = [
  {
    title: '头像',
    dataIndex: 'avatarUrl',
    key: 'avatarUrl',
    width: 80
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName'
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone'
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email'
  },
  {
    title: '角色',
    dataIndex: 'userRole',
    key: 'userRole'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime'
  },
  {
    title: '操作',
    key: 'action',
    width: 200
  }
];

// 表格数据
const userList = ref([]);
const loading = ref(false);
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
});

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true;
  try {
    const res = await listUserVoByPageUsingPost({
      ...searchForm.value,
      current: pagination.value.current,
      pageSize: pagination.value.pageSize,
    });
    userList.value = res.data.records;
    pagination.value.total = res.data.total;
  } catch (error) {
    // 错误处理由拦截器统一处理
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.value.current = 1;
  fetchUserList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    userName: '',
    phone: '',
    userRole: undefined
  };
  handleSearch();
};

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.value = {  // 更新整个分页对象
    ...pagination.value,
    current: pag.current,
    pageSize: pag.pageSize
  };
  fetchUserList();
};

// 编辑用户
const modalVisible = ref(false);
const modalTitle = ref('');
const userForm = ref<API.UserUpdateRequest>({
  id: undefined,
  userName: '',
  email: '',
  phone: '',
  userAvatar: '',
  userRole: USER_ROLE.USER  // 设置默认角色
});

const handleEdit = (record: any) => {
  modalTitle.value = '编辑用户';
  userForm.value = {
    id: record.id,
    userName: record.userName,
    email: record.email,
    phone: record.phone,
    userAvatar: record.avatarUrl,
    userRole: record.userRole
  };
  modalVisible.value = true;
};

const handleModalOk = async () => {
  try {
    const res = await updateUserUsingPost(userForm.value);
    if (res.code === 0) {
      message.success('更新成功');
      modalVisible.value = false;
      fetchUserList();
    }
  } catch (error) {
    // 移除错误处理，由拦截器统一处理
  }
};

// 删除用户
const handleDelete = async (record: any) => {
  try {
    const res = await deleteUserUsingPost({
      id: record.id  // 需要传递对象格式
    });
    if (res.code === 0) {
      message.success('删除成功');
      fetchUserList();
    }
  } catch (error) {
    // 移除错误处理，由拦截器统一处理
  }
};

// 表单规则
const rules = {
  userName: [{ required: true, message: '请输入用户名' }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }]
};

onMounted(() => {
  fetchUserList();
});
</script>

<style scoped>
.user-container {
  padding: 24px;
}

:deep(.ant-avatar) {
  background-color: #1890ff;
}
</style>
